<template>
  <div class="manager-container">
    <div class="app-container">
      <!-- 搜索条件开始-->
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="default"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              class="el-tree"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              :default-expand-all="false"
              @node-click="handleNodeClick"
              node-key="id"
              :default-expanded-keys="[100]"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="用户名称" prop="username">
              <el-input
                v-model="queryParams.username"
                placeholder="请输入用户名称"
                clearable
                size="default"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                size="default"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="default">
                <el-option label="正常" value="0">正常</el-option>
                <el-option label="停用" value="1">停用</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                style="width:240px"
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" size="default" @click="handleQuery">
                <i class="iconfont icon-chaxun">查询</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button size="default" @click="resetQuery">
                <i class="iconfont icon-chongzhi">重置</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="default"
                @click="handleAdd"
              >
                <i class="iconfont icon-tianjia">新增</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="default"
                :disabled="single"
                @click="handleUpdate"
                v-if="permissiones(['system:user:edit'])"
              >
                <i class="iconfont icon-bianji">编辑</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                size="default"
                :disabled="multiple"
                @click="handleDelete"
                v-if="permissiones(['system:user:remove'])"
              >
                <i class="iconfont icon-shanchu">删除</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="default"
                @click="handleImport"
              >
                <i class="iconfont icon-daoru">导入</i>
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                size="default"
                @click="handleExport"
              >
                <i class="iconfont icon-daochu">导出</i>
              </el-button>
            </el-col>
          </el-row>
          <!-- 搜索条件结束 -->
          <!--列表数据开始-->
          <el-table
            :header-cell-style="{background:'#f3f3f3'}"
            :border="true"
            :data="userList"
            @selection-change="handleSelectionChange"
            v-loading="loading"
            height="550"
          >
            <el-table-column type="selection" width="50" align="center"/>
            <!-- <el-table-column label="用户编号" align="center" prop="userId" width="100"/> -->
            <el-table-column
              label="用户名称"
              align="center"
              prop="username"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="用户昵称"
              align="center"
              prop="realName"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="部门"
              align="center"
              prop="departmentName"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="手机号码" align="center" prop="phone" width="120"/>
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.enableFlag"
                  :active-value="0"
                  :inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="160"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="200"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  size="default"
                  type="text"
                  @click="handleUpdate(scope.row)"
                  v-if="permissiones(['system:user:edit'])"
                >编辑</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button
                  plain
                  size="default"
                  type="text"
                  @click="handleDelete(scope.row)"
                  v-if="permissiones(['system:user:remove'])"
                >删除</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-dropdown
                  @command="(command) => handleCommand(command, scope.row)"
                  v-if="
                  permissiones(['system:user:resetPwd', 'system:user:edit'])
                "
                >
                  <span>
                    <i class="iconfont icon-more"></i>更多
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        command="handleResetPwd"
                        v-if="permissiones(['system:user:resetPwd'])"
                      >
                        <i class="iconfont icon-yaoshi"></i>
                        重置密码
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="handleAuthRole"
                        v-if="permissiones(['system:user:edit'])"
                      >
                        <i class="iconfont icon-user"></i>
                        分配角色
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <Pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="pagination"
          />
        </el-col>
        <!--列表数据结束-->
      </el-row>
      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId">
                <tree-select
                  v-model:value="form.deptId"
                  :value="form.deptId"
                  :options="deptOptions"
                  :show-count="true"
                  placeholder="选择归属部门"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="form.userId == undefined" label="用户名称" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名称" maxlength="30"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
                <el-input
                  v-model="form.password"
                  placeholder="请输入用户密码"
                  type="password"
                  maxlength="20"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="form.sex" placeholder="请选择">
                  <el-option label="男" value="0">男</el-option>
                  <el-option label="女" value="1">女</el-option>
                  <el-option label="未知" value="2">未知</el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio label="0">正常</el-radio>
                  <el-radio label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="岗位">
                <el-select v-model="form.postIds" multiple placeholder="请选择">
                  <el-option
                    v-for="item in postOptions"
                    :key="item.postId"
                    :label="item.postName"
                    :value="item.postId"
                    :disabled="item.status == 1"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-select v-model="form.roleIds" multiple placeholder="请选择">
                  <el-option
                    v-for="item in roleOptions"
                    :key="item.roleId"
                    :label="item.roleName"
                    :value="item.roleId"
                    :disabled="item.status == 1"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport"/>是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
            >下载模板</el-link>
          </div>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
//引入消息弹出框
import { ElMessageBox, ElMessage } from "element-plus";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  userExport,
  userdownload
} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import { hasPermi } from "@/utils/auth";
import { getConfigKey } from "@/api/system/config";
//引入公共组件
import Pagination from "@/components/Pagination/index.vue"; //分页
import TreeSelect from "@/components/TreeSelect/index.vue"; //下拉树
export default {
  name: "User",
  components: {
    Pagination,
    TreeSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "childNode",
        label: "departmentName"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: "",
        phonenumber: "",
        status: "",
        departmentName: "",
		offset:0,
      },
      // 列信息
      columns: [
        {
          key: 0,
          label: `用户编号`,
          visible: true
        },
        {
          key: 1,
          label: `用户名称`,
          visible: true
        },
        {
          key: 2,
          label: `用户昵称`,
          visible: true
        },
        {
          key: 3,
          label: `部门`,
          visible: true
        },
        {
          key: 4,
          label: `手机号码`,
          visible: true
        },
        {
          key: 5,
          label: `状态`,
          visible: true
        },
        {
          key: 6,
          label: `创建时间`,
          visible: true
        }
      ],
      // 表单校验
      rules: {
        username: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur"
          }
        ],
        nickName: [
          {
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "用户密码不能为空",
            trigger: "blur"
          },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur"
          }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {},
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // let params = this.$route.query;
    // let keys = Object.keys(params).map(key => key);
    // let kay = keys[0];
    // this.queryParams[kay] = JSON.stringify(params[kay].split(","));
    // console.log("this.queryParams :>> ", this.queryParams);
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /**权限问题 */
    permissiones(value) {
      return hasPermi(value);
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser({
        ...this.queryParams,
        beginTime: this.dateRange ? this.dateRange[0] : null,
        endTime: this.dateRange ? this.dateRange[1] : null
      }).then(response => {
        this.userList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(err=>{
        this.$message.error(err.msg)
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.departmentName = data.departmentName;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      ElMessageBox.confirm(
        '确认要"' + text + '""' + row.username + '"用户吗？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          ElMessage({
            type: "success",
            message: text + "成功"
          });
        })
        .catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        username: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      // this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * 获取分页参数
     */
    pagination({ page, limit }) {
      this.queryParams.pageNum = page;
      this.queryParams.pageSize = limit;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.resetFields();
      // this.resetForm('queryForm')
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      console.log(row, "row");

      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      ElMessageBox.prompt('请输入"' + row.username + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            ElMessage({
              type: "success",
              message: "修改成功，新密码是：" + value
            });
          });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form)
              .then(response => {
                this.$message.success(response.msg);
                this.open = false;
                this.getList();
              })
              .catch(err => {
                this.$message.error(err.msg);
              });
          } else {
            addUser(this.form)
              .then(response => {
                this.$message.success(response.msg);
                this.open = false;
                this.getList();
              })
              .catch(err => {
                this.$message.error(err.msg);
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      ElMessageBox.confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          ElMessage({
            type: "success",
            message: "删除成功"
          });
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      userExport()
        .then(res => {
          const link = document.createElement("a");
          let blob = new Blob([res], {
            type: res.type
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "用户管理统计");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          this.$message.error("导出失败");
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      userdownload()
        .then(res => {
          const link = document.createElement("a");
          let blob = new Blob([res], {
            type: res.type
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "用户管理下载模板");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          this.$message.error("导出失败");
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      ElMessageBox.alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true
      });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="less" scoped>
.el-tree {
  border: solid 1px #eeeeee;
  overflow-y: scroll;
  max-height: 780px;
}
</style>
